<?php

namespace app\api\common\controller;

use app\api\common\library\Auth;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\facade\App;
use think\facade\Config;
use think\facade\Lang;
use think\facade\Request;
use think\Response;
use think\Validate;
use think\cache\driver\Redis;
use think\facade\Cache;
use think\facade\Db;
use EasyWeChat\Factory;


/**
 * API控制器基类
 */
class Api
{

    /**
     * @var Request Request 实例
     */
    protected $request;

    /**
     * @var bool 验证失败是否抛出异常
     */
    protected $failException = false;

    /**
     * @var bool 是否批量验证
     */
    protected $batchValidate = false;

    /**
     * @var array 前置操作方法列表
     */
    protected $beforeActionList = [];

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = [];

    /**
     * 权限Auth
     * @var Auth
     */
    protected $auth = null;

    /**
     * 默认响应输出类型,支持json/xml
     * @var string
     */
    protected $responseType = 'json';

    

    //用户登录信息
    protected $memberLoginData = [];
    protected $user_member_id = 0;

    //店铺登录数据
    protected $storeLoginData = [];
    protected $store_id = 0;//用户ID
    protected $admin_id = 0;


    //微信相关配置
    protected $wx_config = [];
    protected $pay_config = [];

    protected $wxApp = null;

    protected $payApp = null;
    protected $code = 0;
    
    protected $path = "";


    /**
     * 构造方法
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct(Request $request = null)
    {
	$this->request = is_null($request) ? Request::instance() : $request;  
	$this->code=$this->request::param('code','post') ? $this->request::param('code','post') : 0;
        //微信初始化
	$this->wechatInitialization();

        // 控制器初始化
        $this->_initialize();
        //控制器构造方法(独立)
        $this->_structure();
        // 前置操作方法
        if ($this->beforeActionList) {
            foreach ($this->beforeActionList as $method => $options) {
                is_numeric($method) ?
                $this->beforeAction($options) :
                $this->beforeAction($method, $options);
            }
        }
    }
    public function __call($name, $arguments)
    {
        // 如果是API模块，需要输出API的数据格式（一般是json）
        // 如果是模板引擎的方式，需要输出自定义错误页面
        /*$result = [
            'status' => 0,
            'message' => '找不到该方法',
            'result' => null
        ];
        return json($result, 400);*/
        return show(0, "找不到{$name}方法", null, 404);
    }
    

    /**
     * 初始化操作
     * @access protected
     */
    protected function _initialize()
    {
        //跨域请求检测
        check_cors_request();
    
        //移除HTML标签
        $this->request::filter('trim,strip_tags,htmlspecialchars');

        $this->auth = Auth::instance();

        $modulename     = 'app\api\controller\\';
        $controllername = $modulename . $this->request::controller();
        $actionname     = strtolower($this->request::action());

        // token
        $token = $this->request::server('HTTP_TOKEN', $this->request::request('token', \think\facade\Cookie::get('token')));
        //token校验
    	$path = str_replace('.', '/', $controllername) . '/' . $actionname;
    	$noNeedLogin = [
    	    'app\api\controller\Wx/getbaseinfo',
    	    'app\api\controller\home/City/getcity',
    	    'app\api\controller\Card/cardlist',
    	    'app\api\controller\store/Carefully/getstorecoupon',
    	    'app\api\controller\Member/drawcontent',
    	    'app\api\controller\Card/cardlist',
    	    'app\api\controller\TakeCoupon/getcouponcount',
    	    'app\api\controller\Member/nickname'
    	    
    	];
    	$this->path = $path;
	    if($token !=null || $token !=""){
	        if(in_array($path,$noNeedLogin) == false){
		        $this->checkToken($token);
            }
        }

    }

    protected function _structure(){
        
    }
    protected function wechatInitialization(){
        $this->wx_config = config('wx.wx_config');
        $this->pay_config = config('wx.pay_config');
        
        $this->wxApp = Factory::miniProgram($this->wx_config);
        
        $this->payApp = Factory::payment($this->pay_config);
        
    }
    /*
    order_type:订单类型
     */
    protected function prepareOnlinePay($order_id,$amount){
        $base = time();
        $out_trade_no = createSerialNumber();
        if($this->user_member_id == 626){
            $amount = 1;
        }
        $this->user_member_id = 1341;
        $result = $this->payApp->order->unify([
          'body' => '测试充值',
          'out_trade_no' => $out_trade_no,
          'total_fee' => $amount*100,
          'trade_type' => 'JSAPI',
          'openid' => 'ojTtY5YnQnU9vwe8q3oOfYVJX2hI',//Db::name('members') -> where(['members_id' => $this->user_member_id]) -> value('members_openid'),
        ]);
   
        $jssdk = $this->payApp->jssdk;
        $json = $jssdk->bridgeConfig($result['prepay_id'],false); // 返回数组
        $data['flow_id']=$out_trade_no;
        $data['amount']=$amount;
        $data['status']=0;
        $data['created_at']=date('Y-m-d H:i:s');
        $data['orders_id']=$order_id;
        $data['prepayid'] = $result['prepay_id'];
        $id = Db::name('wechat_payment') -> insertGetId($data);
      
        return $json;
    }
    /*
    order_type:订单类型
    扫码支付
     */
    protected function prepareOfflinePay($order_id,$amount,$order_type=2){
        $out_trade_no = createSerialNumber($order_type);
        $base = time(); 
        $result = $this->payApp->order->unify([
          'body' => '车美佳服务订单',
          'out_trade_no' => $out_trade_no,
          'product_id' => $order_id,
          'total_fee' => $amount*100,
          'trade_type' => 'NATIVE',
        ]);
        $data['flow_id']=$out_trade_no;
        $data['amount']=$amount;
        $data['status']=0;
        $data['created_at']=date('Y-m-d H:i:s');
        $data['orders_id']=$order_id;
        $data['prepayid'] = $result['prepay_id'];
        $data['member_id'] = 0;
        $data['info'] = json_encode($result);
        $data['order_type']=$order_type;
        $id = Db::name('wechat_payment') -> insertGetId($data);
        //$result['code_url'];
        //halt($result['code_url']); 
        return $result['code_url'];
    }

    /**
     * 加载语言文件
     * @param string $name
     */
    protected function loadlang($name)
    {
        $name = ($name);
        Lang::load('./app/api' . '/lang/' . '/' . str_replace('.', '/', $name) . '.php');
    }

    /**
     * 操作成功返回的数据
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为1
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
     */
    protected function success($msg = '', $data = null, $code = 1, $type = 'jsonp', array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 操作失败返回的数据
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为0
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
     */
    protected function error($msg = '', $data = null, $code = 0, $type = 'jsonp', array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed  $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为0
     * @param string $type   输出类型，支持json/xml/jsonp
     * @param array  $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => $data,
        ];
        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request::param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }

    /**
     * 前置操作
     * @access protected
     * @param string $method  前置操作方法名
     * @param array  $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
     * @return void
     */
    protected function beforeAction($method, $options = [])
    {
        if (isset($options['only'])) {
            if (is_string($options['only'])) {
                $options['only'] = explode(',', $options['only']);
            }

            if (!in_array($this->request::action(), $options['only'])) {
                return;
            }
        } elseif (isset($options['except'])) {
            if (is_string($options['except'])) {
                $options['except'] = explode(',', $options['except']);
            }

            if (in_array($this->request::action(), $options['except'])) {
                return;
            }
        }

        call_user_func([$this, $method]);
    }

    /**
     * 设置验证失败后是否抛出异常
     * @access protected
     * @param bool $fail 是否抛出异常
     * @return $this
     */
    protected function validateFailException($fail = true)
    {
        $this->failException = $fail;

        return $this;
    }

    /**
     * 验证数据
     * @access protected
     * @param array        $data     数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @param array        $message  提示信息
     * @param bool         $batch    是否批量验证
     * @param mixed        $callback 回调方法（闭包）
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            // 支持场景
            if (strpos($validate, '.')) {
                list($validate, $scene) = explode('.', $validate);
            }

            $v = validate($validate);

            !empty($scene) && $v->scene($scene);
        }

        // 批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }
        // 设置错误信息
        if (is_array($message)) {
            $v->message($message);
        }
        // 使用回调验证
        if ($callback && is_callable($callback)) {
            call_user_func_array($callback, [$v, &$data]);
        }

        if (!$v->check($data)) {
            if ($this->failException) {
                throw new ValidateException($v->getError());
            }

            return $v->getError();
        }

        return true;
    }
    /**
     * Token校验
     */
    protected function checkToken($token){

        if($token == null){
            $this->error("token不能为空", null, config("status.access_token_null"),"json");
	}
	$token = stripslashes($token);
        $decodeToken = authcode($token,'DECODE',config('token.key'),0);
        //halt($decodeToken);
        $decodeTokenArr = explode('||',$decodeToken);
        if($decodeTokenArr[0] != config('token.str')){
            $this->error("无效的token", [], config("status.access_token_invilidate"),"json");
        }
        $this->user_member_id = $decodeTokenArr[1] ? $decodeTokenArr[1] : 0;
        $this->store_id = $decodeTokenArr[1] ? $decodeTokenArr[1] : 0;
        $this->admin_id = isset($decodeTokenArr[2]) ? $decodeTokenArr[2] : 0;
        $key = config('token.memberprefix')."-".$this->user_member_id;
        $storeKey = Config::get('token.storeprefix')."-".$this->store_id.'-'.$this->admin_id;
        $redis = Cache::store('redis');

        //halt($token == "002ar3grd5mjTmdPodlP3u5+tfzrS13ovyU8F4C9SnODQjJKivt0YIJu3BQ");
        /*$data[0] = $redis->get($storeKey);
        $data[1] = $token;
        halt($data);*/
        if($redis->get($key) != null && $redis->get($key) != $token || $redis->get($storeKey) != null && $redis->get($storeKey) != $token){

            $this->user_member_id = 0;
	    $this->store_id = 0;
	    $this->store_id = 0;
            $this->wxApp = Factory::miniProgram($this->wx_config);
            if($this->path == "app\api\controller\Wx/login"){
                $loginInfo = $this->wxApp->auth->session($this->code);
            }else{
                $loginInfo = [];
            }
            $this->error("无效的key值", $loginInfo, config("status.key_invalidate"),"json");
        }
        if($redis->get($key) == null && $redis->get($storeKey) == null){
            $this->user_member_id = 0;
	        $this->store_id = 0;
    	    $this->wxApp = Factory::miniProgram($this->wx_config);
    	    if($this->path == "app\api\controller\Wx/login"){
                $loginInfo = $this->wxApp->auth->session($this->code);
            }else{
                $loginInfo = [];
            }
            $this->error("token已过期,请重新登录",$loginInfo, config("status.access_token_expired"),"json");
	}
	if($redis->TTL($key) == -1){

              $this->wxApp = Factory::miniProgram($this->wx_config);
              if($this->path == "app\api\controller\Wx/login"){
                  $loginInfo = $this->wxApp->auth->session($this->code);
              }else{
                $loginInfo = [];
              }
              $this->error("token已过期,请重新登录",$loginInfo, config("status.access_token_expired"),"json");

	}
        //返回登录信息
        if($redis->get($key)){
	    $loginUser = Db::name('members') -> where('members_id',$this->user_member_id) -> findOrEmpty();
            $loginUser['members_nickname'] = base64_decode($loginUser['members_nickname']);
            $data = [
                 "accessToken" => $token,
                 "tokenExpired" => $redis->TTL($key),
                 "user" => $loginUser
	 ];
	    
            $this->store_id = 0;
            $this->memberLoginData = $data;
        }
        if($redis->get($storeKey)){
	    $loginStore = Db::name('store') -> where('store_id',$this->store_id) -> field('store_id,store_name,store_address,store_image') -> findOrEmpty();
            $loginStore['store_image'] = (explode('|', $loginStore['store_image']))[0];
            $data = [
                "accessToken" => $token,
                "tokenExpired" => $redis->TTL($storeKey),
                "storeInfo" => $loginStore
            ];
            $this->user_member_id = 0;
	    $this->storeLoginData = $data;
	    Db::name('store_login_history') -> insertGetId(['store_id' => $this->store_id,'admin_id' => $this->admin_id,'token' => $token,'create_time' => time()]);



        }
        

    }


}
